package com.cleaningcloud.auth.service;

import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.cleaningcloud.cld.api.RemoteStaffService;
import com.cleaningcloud.cld.api.domain.CldStaff;
import com.cleaningcloud.cld.api.model.LoginStaff;
import com.cleaningcloud.cld.api.model.LoginValidateInfo;
import com.cleaningcloud.cld.api.model.RegisterStaff;
import com.cleaningcloud.common.core.constant.SecurityConstants;
import com.cleaningcloud.common.core.domain.R;
import com.cleaningcloud.common.core.exception.ServiceException;
import com.cleaningcloud.common.core.utils.StringUtils;
import com.cleaningcloud.common.redis.service.RedisService;
import com.cleaningcloud.common.security.utils.SecurityUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class MiniLoginService {

    @Autowired
    private RedisService redisService;

    @Autowired
    private MiniPasswordService passwordService;

    @Autowired
    private RemoteStaffService remoteStaffService;


    /**
     * @Author Shaw
     * @Description 云管理(小程序)用户登录
     * @date: 2025-03-31 16:39
     * @param: //TODO
     */
    public LoginStaff login(String staffPhone, String password)
    {
        // 手机号或密码为空 错误
        if (StringUtils.isAnyBlank(staffPhone, password))
        {
            throw new ServiceException("手机号/密码必须填写");
        }
        // 查询员工信息
        R<LoginStaff> staffResult = remoteStaffService.getStaffInfo(staffPhone, SecurityConstants.INNER);
        if (R.FAIL == staffResult.getCode())
        {
            throw new ServiceException(staffResult.getMsg());
        }

        LoginStaff staffInfo = staffResult.getData();
        //staffInfo.getCldStaff().setOpenId(json.get("openid").toString());
        LoginValidateInfo loginValidateInfo = getLoginValidateInfo(staffResult, staffInfo);
        passwordService.validate(loginValidateInfo, password);
        return staffInfo;
    }
    @NotNull
    private LoginValidateInfo getLoginValidateInfo(R<LoginStaff> staffResult, LoginStaff staffInfo) {
        LoginValidateInfo loginValidateInfo = new LoginValidateInfo();
        if(staffInfo.getLoginType() == 1){
            CldStaff cldStaff = staffResult.getData().getCldStaff();
            if (3 == cldStaff.getStaffStatus())
            {
                throw new ServiceException("离职状态不允许登录");
            }
            if (4 == cldStaff.getStaffStatus())
            {
                throw new ServiceException("已被拉入黑名单,请联系系统管理员");
            }
            loginValidateInfo.setPhone(cldStaff.getStaffPhone());
            loginValidateInfo.setPassword(cldStaff.getStaffPassword());
        }else if(staffInfo.getLoginType() == 2){

            loginValidateInfo.setPhone(staffInfo.getProjectAccount().getUserPhone());
            loginValidateInfo.setPassword(staffInfo.getProjectAccount().getPassWord());
        }else if(staffInfo.getLoginType() == 3){
            String postId = staffInfo.getPostId();
            if(( StringUtils.isEmpty(postId) || !postId.equals("2") && !postId.equals("10") && !postId.equals("-1"))){
                throw new ServiceException("系统用户只允许经理/维修师/审核员登录");
            }
            loginValidateInfo.setPhone(staffInfo.getPhone());
            loginValidateInfo.setPassword(staffInfo.getPassword());
        }
        return loginValidateInfo;
    }

    /**
     * @Author Shaw
     * @Description 云管理(小程序)用户注册
     * @date: 2025-03-31 16:40
     * @param: //TODO
     */
    public void register(RegisterStaff registerStaff)
    {
        // 校验验证码是否正确
        String code = redisService.getCacheObject(registerStaff.getPhone());
        if(code == null){
            throw new ServiceException("验证码已失效！");
        }
        if(StringUtils.isEmpty(registerStaff.getCode())){
            throw new ServiceException("验证码不能为空！");
        }
        if(!code.equals(registerStaff.getCode())){
            throw new ServiceException("传入的验证码错误！");
        }
        CldStaff cldStaff = new CldStaff();
        cldStaff.setStaffPassword(SecurityUtils.encryptPassword("123456"));
        cldStaff.setStaffPhone(registerStaff.getPhone());
        cldStaff.setStaffName(registerStaff.getStaffName());
        cldStaff.setStaffIdcard(registerStaff.getStaffIdcard());
        R<?> registerResult = remoteStaffService.registerStaffInfo(cldStaff, SecurityConstants.INNER);

        if (R.FAIL == registerResult.getCode())
        {
            throw new ServiceException(registerResult.getMsg());
        }
    }

    /**
     * @Author Shaw
     * @Description 访问第三方接口
     * @date: 2025-10-16 14:37
     * @param: //TODO
     */
    public JSONObject getHttpUrlResult(StringBuilder url){
        try {
            HttpClient client = HttpClientBuilder.create().build();//构建一个Client
            HttpGet get = new HttpGet(url.toString());    //构建一个GET请求
            HttpResponse response = client.execute(get);//提交GET请求
            HttpEntity result = response.getEntity();//拿到返回的HttpResponse的"实体"
            String content = EntityUtils.toString(result);
            cn.hutool.json.JSONObject res = JSONUtil.parseObj(content);//把信息封装为json
            return res;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
